﻿using HCQ2_Common;
using HCQ2_Model;
using HCQ2_Model.DocModel;
using HCQ2_Model.ViewModel;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace HCQ2UI_Logic.DocumentController
{
    /// <summary>
    ///  文档：用户授权管理控制器
    /// </summary>
    public class DocEmpowerController: BaseLogic
    {
        #region 1.0 默认首次进入文档管理界面 + ActionResult DocList()
        /// <summary>
        ///  1.0 默认首次进入文档管理界面
        /// </summary>
        /// <returns></returns>
        [HCQ2_Common.Attributes.Load]
        [HCQ2_Common.Attributes.Element]
        [HttpGet]
        public ActionResult EmpowerList()
        {
            return View();
        }
        #endregion

        #region 1.1 初始化列表 + ActionResult InitTable()
        /// <summary>
        ///  初始化列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult InitTable()
        {
            string powerName = RequestHelper.GetDeStrByName("powerName"),
                startDate = RequestHelper.GetStrByName("startDate"),
                endDate = RequestHelper.GetStrByName("endDate");
            int page = RequestHelper.GetIntByName("page"),
                rows = RequestHelper.GetIntByName("rows"),
                powerStatus = RequestHelper.GetIntByName("powerStatus");
            TableModel tModel = operateContext.bllSession.T_DocEmpower.GetPowerListData(powerName, startDate, endDate, powerStatus, page, rows);
            return Json(tModel, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 1.2 添加授权 +ActionResult AddPowerByObj(EmpowerListModel power)
        /// <summary>
        ///  添加授权
        /// </summary>
        /// <param name="role"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult AddPowerByObj(EmpowerListModel power)
        {
            if (string.IsNullOrEmpty(power.login_name))
                return operateContext.RedirectAjax(1, "用户登录名为空~", "", "");
            try
            {
                int auto_num = RequestHelper.GetIntByName("auto_num");//批量添加条数
                if(auto_num>50)
                    return operateContext.RedirectAjax(1, "一次批量添加条数不能超过50条~", "", "");
                auto_num = auto_num <= 0 ? 1 : auto_num;
                T_User user = operateContext.bllSession.T_User.Select(s => s.login_name.Equals(power.login_name)).FirstOrDefault();
                if(user==null)
                    return operateContext.RedirectAjax(1, "用户登录名不存在~", "", "");
                for (int i=0;i< auto_num;i++)
                {
                    T_DocEmpower p = new T_DocEmpower
                    {
                        num_code = power.num_code,
                        user_id = user.user_id,
                        limit_code = "VRPPT_ACCESS",
                        status = power.status,
                        start_date = (!string.IsNullOrEmpty(power.start_date) ? DateTime.ParseExact(power.start_date, "yyyy-MM-dd hh:mm:ss", new System.Globalization.CultureInfo("zh-CN")) : (DateTime?)null),
                        end_date = (!string.IsNullOrEmpty(power.end_date) ? DateTime.ParseExact(power.end_date, "yyyy-MM-dd hh:mm:ss", new System.Globalization.CultureInfo("zh-CN")) : (DateTime?)null),
                        machine_code = power.machine_code,
                        machine_name = power.machine_name,
                        reg_id = operateContext.Usr.user_id,
                        reg_name = operateContext.Usr.user_name,
                        update_id = operateContext.Usr.user_id,
                        update_name = operateContext.Usr.user_name,
                        doc_note = power.doc_note
                    };
                    int mark = operateContext.bllSession.T_DocEmpower.Add(p);
                }
                return operateContext.RedirectAjax(0, "授权成功~", "", "");
            }
            catch (Exception ex)
            {
                return operateContext.RedirectAjax(0, ex.Message, "", "");
            }
        }
        #endregion

        #region 1.3 编辑授权 +ActionResult EditPowerByObj(EmpowerListModel power)
        /// <summary>
        ///  编辑授权
        /// </summary>
        /// <param name="role"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult EditPowerByObj(EmpowerListModel power)
        {
            if (power.id<=0)
                return operateContext.RedirectAjax(1, "数据验证失败~", "", "");
            try
            {
                T_User user = operateContext.bllSession.T_User.Select(s => s.login_name.Equals(power.login_name)).FirstOrDefault();
                if(user==null)
                    return operateContext.RedirectAjax(1, "授权登录用户不存在~", "", "");
                T_DocEmpower p = new T_DocEmpower
                {
                    user_id = user.user_id,
                    num_code = power.num_code,
                    status = power.status,
                    start_date = (!string.IsNullOrEmpty(power.start_date) ? DateTime.ParseExact(power.start_date, "yyyy-MM-dd hh:mm:ss", new System.Globalization.CultureInfo("zh-CN")) : (DateTime?)null),
                    end_date = (!string.IsNullOrEmpty(power.end_date) ? DateTime.ParseExact(power.end_date, "yyyy-MM-dd hh:mm:ss", new System.Globalization.CultureInfo("zh-CN")) : (DateTime?)null),
                    machine_code = power.machine_code,
                    machine_name = power.machine_name,
                    update_id = operateContext.Usr.user_id,
                    update_name = operateContext.Usr.user_name,
                    doc_note = power.doc_note
                };
                operateContext.bllSession.T_DocEmpower.Modify(p, s => s.id == power.id, "user_id", "num_code", "status", "start_date", "end_date", "machine_code", "machine_name", "update_id", "update_name", "doc_note");
                return operateContext.RedirectAjax(0, "数据更新成功~", "", "");
            }
            catch (Exception ex)
            {
                return operateContext.RedirectAjax(0, ex.Message, "", "");
            }
        }
        #endregion  

        #region 1.4 删除授权 +ActionResult DelUser()
        /// <summary>
        ///  删除授权
        /// </summary>
        /// <param name="id">授权id</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult DelPowerById()
        {
            string pid = RequestHelper.GetStrByName("pId");
            if (string.IsNullOrEmpty(pid))
                return operateContext.RedirectAjax(1, "需要删除的数据不存在~", "", "");
            string[] ids = pid.Split(',');
            foreach (var id in ids)
                operateContext.bllSession.T_DocEmpower.Delete(s => s.id == Helper.ToInt(id));
            return operateContext.RedirectAjax(0, "数据删除成功~", "", "");
        }
        #endregion

        #region 1.5 批量导入授权用户 + ActionResult ImportUser(HttpPostedFileBase excelFile)
        /// <summary>
        ///  批量导入授权用户
        /// </summary>
        /// <param name="excelFile">授权用户</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ImportUser(HttpPostedFileBase excelFile)
        {
            try
            {
                if (excelFile == null)
                    return operateContext.RedirectAjax(1, "请选择导入文件！", "", "");
                if (!Path.GetExtension(excelFile.FileName).Equals(".xlsx"))
                    return operateContext.RedirectAjax(1, "导入文件是.xlsx格式的excel文件！", "", "");
                //新的文件名
                string batchCode = Helper.GetGuid;
                #region 导入文件到临时目录
                string path = Server.MapPath("~/UpFile/ImportWord/temp/");
                if (!Directory.Exists(path.ToString()))
                    Directory.CreateDirectory(path.ToString());//文件夹不存在则创建
                string tempPath = Server.MapPath("~/UpFile/ImportWord/temp/") + batchCode + ".xlsx";
                excelFile.SaveAs(tempPath);
                #endregion
                Stopwatch sw1 = new Stopwatch();
                sw1.Start();
                bool importUser;
                List<string> mess = operateContext.bllSession.T_DocEmpower.importUser(tempPath,operateContext.Usr, out importUser);
                sw1.Stop();
                if (importUser)
                    return operateContext.RedirectAjax(0, string.Format("导入成功 用时：{0}秒。", Math.Round((double)sw1.ElapsedMilliseconds / 1000, 2)), (mess.Count > 0 ? mess : null), "");
                //导入成功删除临时文件
                if (System.IO.File.Exists(tempPath))
                    System.IO.File.Delete(tempPath);
                return operateContext.RedirectAjax(1, "数据导入失败~", mess, "");
            }
            catch (Exception ex)
            {
                return operateContext.RedirectAjax(1, ex.Message, "", "");
            }
        }
        #endregion
    }
}
